import { STORAGE_KEY_STATS } from './constants';

// 生成唯一 ID
const generateId = (length = 10) => {
  const parts = (+new Date()).toString().split('').reverse();
  let id = '';

  for (let i = 0; i < length; ++i) {
    id += parts[Math.floor(Math.random() * parts.length)];
  }

  return id;
};

export const getDeviceId = () => {
  let id = '';

  const data = JSON.parse(localStorage.getItem(STORAGE_KEY_STATS) ?? '{}') || {};

  if (data.deviceId) {
    id = data.deviceId;
  }
  else {
    id = generateId();
    data.deviceId = id?.trim?.() ?? id;
    localStorage.setItem(STORAGE_KEY_STATS, JSON.stringify(data));
  }

  return id;
};
